package com.closer.service.biz.ai.core.handler;

import com.closer.service.biz.chatHistory.enums.ChatHistoryMessageTypeEnum;
import com.closer.service.biz.chatHistory.service.ChatHistoryService;
import com.closer.service.biz.user.dto.vo.LoginUserVO;
import com.closer.service.biz.user.entity.User;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Flux;

/**
 * 简单稳步流处理器
 * 处理HTML 和MULTI_FILE 类型的流式响应
 */
@Slf4j
public class SimpleTextStreamHandler {

    public Flux<String> handle(Flux<String> originFlux,
                                    ChatHistoryService chatHistoryService,
                                    long appId, LoginUserVO loginUser){
        var aiResponseBuilder = new StringBuilder();
        return originFlux
                .map(chunk -> {
                    //收集AI响应内容
                    aiResponseBuilder.append(chunk);
                    return chunk;
                })
                .doOnComplete(()->{
                    //流式响应完成后，添加AI消息到对话历史
                    var aiResponse =aiResponseBuilder.toString();
                    chatHistoryService.addChatMessage(appId,aiResponse, ChatHistoryMessageTypeEnum.AI.getValue(),loginUser.getId());
                })
                .doOnError(error -> {
                    //如果AI回复失败，也要记录错误消息
                    var errorMessage ="AI回复错误：" +  error.getMessage();
                    chatHistoryService.addChatMessage(appId,errorMessage, ChatHistoryMessageTypeEnum.AI.getValue(), loginUser.getId());
                });
    }
}
